<template>
  <div class="app-container">
    <vxe-grid
      ref="gridRef"
      v-bind="gridOptions"
      @toolbar-button-click="toolbarButtonClickEvent"
      @form-submit="formSubmitEvent"
      @form-reset="formResetEvent"
    >
      <template #active="{ row }">
        <vxe-button
          mode="text"
          status="primary"
          content="编辑"
          icon="vxe-icon-edit"
          @click="updateRow(row)"
        ></vxe-button>
        <vxe-button
          mode="text"
          status="primary"
          content="删除"
          icon="vxe-icon-edit"
          @click="deleteData(row)"
        ></vxe-button>
        <vxe-button
          mode="text"
          status="primary"
          content="质检报告下载"
          icon="vxe-icon-edit"
          @click="downloadTmp(row)"
        ></vxe-button>
        <!-- <vxe-button
          mode="text"
          status="primary"
          content="模板上传"
          icon="vxe-icon-edit"
          @click="uploadTmp(row)"
        ></vxe-button> -->

        <vxe-button
          mode="text"
          status="primary"
          content="填写数据"
          icon="vxe-icon-edit"
          @click="fillDate(row)"
        ></vxe-button>
      </template>
    </vxe-grid>
    <!--质检任务修改-->
    <vxe-modal v-model="showPopup" v-bind="modalOptions" :loading="loading">
      <template #default>
        <vxe-form
          v-bind="formOptions"
          @submit="submitEvent"
          @reset="resetEvent"
        ></vxe-form>
      </template>
    </vxe-modal>

    <vxe-modal
      v-model="showPopup2"
      v-bind="modalOptions"
      show-confirm-button
      show-footer
      :loading="loading"
      @confirm="confirmEvent"
    >
      <template #default>
        <vxe-upload
          v-model="fileList"
          multiple
          :upload-method="uploadMethod"
        ></vxe-upload>
      </template>
    </vxe-modal>

    <vxe-modal
      v-model="showPopup3"
      v-bind="modalOptions"
      show-confirm-button
      show-footer
      :loading="loading"
      @confirm="confirmEvent2"
    >
      <div style="height: 15%">
        <vxe-form
          style="height: 100%"
          ref="formRef"
          :border="border"
          :title-background="titleBackground"
          vertical-align="center"
          title-width="100"
          v-bind="formOptions2"
        >
        </vxe-form>
      </div>

      <div style="height: 80%">
        <vxe-tabs
          v-model="selectTab"
          @change="tabChangeEvent"
          position="left"
          type="round-card"
          style="height: 100%"
        >
          <vxe-tab-pane title="性能" name="性能">
            <tmp-samp-item :row-data="selectData" />
          </vxe-tab-pane>
          <vxe-tab-pane title="外观" name="外观">
            <tmp-samp-item :row-data="selectData" />
          </vxe-tab-pane>
          <vxe-tab-pane title="包装及标识" name="包装及标识">
            <tmp-samp-item :row-data="selectData" />
          </vxe-tab-pane>
          <vxe-tab-pane title="尺寸" name="尺寸">
            <tmp-samp-item :row-data="selectData" />
          </vxe-tab-pane>
          <vxe-tab-pane title="接口卷比例" name="接口卷比例">
            <tmp-samp-item :row-data="selectData" />
          </vxe-tab-pane>
        </vxe-tabs>
      </div>
    </vxe-modal>

    <vxe-modal
      v-model="showPopup4"
      v-bind="modalOptions4"
      show-confirm-button
      show-footer
      :loading="loading"
      @confirm="confirmEvent3"
    >
      <vxe-form
        ref="formRef"
        :border="border"
        :title-background="titleBackground"
        vertical-align="center"
        title-width="100"
        :rules="formRules"
        :data="formData"
      >
        <template v-for="todo in todos" :key="todo.code">
          <vxe-form-item :title="todo.name" span="12">
            <template #default="{ data }">
              <vxe-input
                v-model="todo.value"
                @keydown.enter="inputEnter(data.scanBarcode)"
              ></vxe-input>
            </template>
          </vxe-form-item>
        </template>
      </vxe-form>
    </vxe-modal>
  </div>
</template>

<script>
import {
  getInspectionTaskByPage,
  addInspectionTask,
  addInspectionTasks,
  delInspectionTask,
  uploadFile,
  getValueTmpByTaskId,
  fillInspectionTaskValue,
  getInspectionTaskTemplateSamplingItemByPage,
  fillInspectionSamplingTaskValue,
  fillInspectionTaskValueExt,
} from "@/api/quality/inspectionTask";

import {
  getMaterialByPage,
  addMaterial,
  delMaterial,
  uploadMaterialExcel,
  addInspectionTemplateMaterial,
} from "@/api/baseData/material";

import {
  getInspectionTemplateByPage,
  addInspectionTemplate,
  delInspectionTemplate,
} from "@/api/quality/inspectionTemplate";
import { download } from "@/utils/request";

import { VxeUI } from "vxe-pc-ui";

import { useRouter, useRoute } from "vue-router";
import { serialize } from "xe-utils";
import TmpSampItem from "./base/inspectionTaskTemplateSamplingItem.vue";
const router = useRouter();
const findPageList = async (page) => {
  await getMaterialByPage(page);
};
export default {
  components: {
    TmpSampItem,
  },
  data() {
    const selectData = { id: 0, fillType: "性能", materialCode: "" };
    const selectSubData = { id: 0 }; //这个是检验项数据
    const fileList = [];
    const gridOptions = {
      sortConfig: {
        remote: true,
      },
      loading: false,
      stripe: true,
      showOverflow: true,
      showFooter: true,
      height: 800,
      columnConfig: {
        resizable: true,
        drag: true,
      },
      columnDragConfig: {
        trigger: "cell",
        showIcon: false,
        showGuidesStatus: true,
      },
      rowConfig: {
        isHover: true,
      },
      resizableConfig: {
        isDblclickAutoWidth: true,
      },
      pagerConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
      },
      toolbarConfig: {
        refresh: true,
        import: true,
        export: true,
        print: true,
        zoom: true,
        custom: true,
        buttons: [
          { name: "新增", code: "myAdd", status: "primary" },
          { name: "删除", code: "myDel", status: "error" },

          // { name: "保存", code: "mySave", status: "success" },
        ],
      },
      formConfig: {
        data: {
          name: "",
          role: "",
          sex: "",
          num: "",
          address: "",
        },
        items: [
          {
            field: "name",
            title: "名称",
            span: 6,

            itemRender: { name: "VxeInput", props: { clearable: true } },
          },
          {
            field: "code",
            title: "编码",
            span: 6,

            itemRender: { name: "VxeInput", props: { clearable: true } },
          },

          {
            field: "createTime",
            title: "时间",
            span: 6,

            itemRender: {
              name: "VxeDatePicker",
              props: {
                multiple: true,
                clearable: true,
              },
            },
          },

          {
            align: "right",
            span: 6,
            itemRender: {
              name: "VxeButtonGroup",
              options: [
                { type: "submit", content: "搜索", status: "primary" },
                { type: "reset", content: "重置" },
              ],
            },
          },
        ],
      },
      columns: [
        { type: "checkbox", width: 60 },
        { field: "seq", type: "seq", width: 70 },

        { field: "orNo", title: "单号", sortable: true, width: 180 },
        {
          field: "materialCode",
          title: "物料编码",
          sortable: true,
          width: 180,
        },
        // {
        //   field: "inspectionTemplateName",
        //   title: "质检模板名称",
        //   sortable: true,
        //   width: 180,
        // },
        {
          field: "qty",
          title: "数量",
          sortable: true,
          width: 180,
        },
        
        {
          field: "status",
          title: "状态",
          sortable: true,
          width: 180,
        },
        { field: "createBy", title: "创建人", width: 180 },
        { field: "createTime", title: "创建时间", width: 400 },
        {
          field: "active",
          title: "操作",
          fixed: "right",
          width: 600,
          slots: { default: "active" },
        },
      ],
      scrollX: {
        gt: 0,
        enabled: true,
      },
      scrollY: {
        gt: 0,
        enabled: true,
      },
      proxyConfig: {
        // props: {
        //   result: 'result', // 配置响应结果列表字段
        //   total: 'page.total' // 配置响应结果总页数字段
        // },

        sort: true,
        form: true,
        ajax: {
          query: async ({ page, sorts, form }) => {
            console.log(page, sorts, form, "----");
            // 默认接收 Promise<{ result: [], page: { total: 100 } }>
            let result = await getInspectionTaskByPage({
              ...page,
              ...form,
            });
            return {
              result: result.data.records,
              page: {
                total: result.data.total,
              },
            };
          },
        },
      },
    };
    const gridOptions2 = {
      editConfig: {
        trigger: "click",
        mode: "cell",
        // beforeEditMethod({ row }) {
        //   // name 为 'x' 开头的列禁止编辑
        //   if ((row.name || "").indexOf("x") === 0) {
        //     return false;
        //   }
        //   // age 小于 27 的列禁止编辑
        //   if (row.age < 27) {
        //     return false;
        //   }
        //   // sex 值编辑为 1 的列禁止编辑
        //   if (row.sex === "Women") {
        //     return false;
        //   }
        //   return true;
        // },
      },
      sortConfig: {
        remote: true,
      },
      loading: false,
      stripe: true,
      showOverflow: true,
      showFooter: true,
      height: "100%",
      columnConfig: {
        resizable: true,
        drag: true,
      },
      columnDragConfig: {
        trigger: "cell",
        showIcon: false,
        showGuidesStatus: true,
      },
      rowConfig: {
        isHover: true,
      },
      resizableConfig: {
        isDblclickAutoWidth: true,
      },
      pagerConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
      },
      // toolbarConfig: {
      //   refresh: true,
      //   import: true,
      //   export: true,
      //   print: true,
      //   zoom: true,
      //   custom: true,
      //   buttons: [
      //     { name: "新增", code: "myAdd", status: "primary" },
      //     { name: "删除", code: "myDel", status: "error" },

      //     // { name: "保存", code: "mySave", status: "success" },
      //   ],
      // },
      formConfig: {
        data: {
          name: "",
          role: "",
          sex: "",
          num: "",
          address: "",
        },
        items: [
          {
            field: "name",
            title: "名称",
            span: 6,

            itemRender: { name: "VxeInput", props: { clearable: true } },
          },
          {
            field: "code",
            title: "编码",
            span: 6,

            itemRender: { name: "VxeInput", props: { clearable: true } },
          },

          {
            field: "createTime",
            title: "时间",
            span: 6,

            itemRender: {
              name: "VxeDatePicker",
              props: {
                multiple: true,
                clearable: true,
              },
            },
          },

          {
            align: "right",
            span: 6,
            itemRender: {
              name: "VxeButtonGroup",
              options: [
                { type: "submit", content: "搜索", status: "primary" },
                { type: "reset", content: "重置" },
              ],
            },
          },
        ],
      },
      columns: [
        { type: "checkbox", width: 60 },
        // { field: "fillType", title: "分类", width: 70 },
        {
          field: "inspectionItemName",
          title: "检验项",
          sortable: true,
          width: 100,
        },
        { field: "fillQty", title: "检验量", sortable: true, width: 100 },
        { field: "sequence", title: "序列号", sortable: true, width: 100 },
        {
          field: "samplingName",
          title: "抽样方案",
          sortable: true,
          width: 100,
        },
        {
          field: "value1",
          title: "值1",
          editRender: { name: "VxeInput" },
          slots: { edit: "value_1" },
          width: 100,
        },
        {
          field: "value2",
          title: "值2",
          sortable: true,
          editRender: { name: "VxeInput" },
          slots: { edit: "value_2" },
          width: 100,
        },
        {
          field: "value3",
          title: "值3",
          sortable: true,
          width: 100,
          editRender: { name: "VxeInput" },
          slots: { edit: "value_3" },
        },
        // {
        //   field: "value4",
        //   title: "值4",
        //   sortable: true,
        //   width: 180,
        //   editRender: { name: "VxeInput" },
        //   slots: { edit: "value_4" },
        // },
        // {
        //   field: "value5",
        //   title: "值5",
        //   sortable: true,
        //   width: 180,
        //   editRender: { name: "VxeInput" },
        //   slots: { edit: "value_5" },
        // },
        {
          field: "active",
          title: "操作",
          fixed: "right",
          width: 200,
          slots: { default: "active" },
        },
      ],
      scrollX: {
        gt: 0,
        enabled: true,
      },
      scrollY: {
        gt: 0,
        enabled: true,
      },
      proxyConfig: {
        // props: {
        //   result: 'result', // 配置响应结果列表字段
        //   total: 'page.total' // 配置响应结果总页数字段
        // },

        sort: true,
        form: true,
        ajax: {
          query: async ({ page, sorts, form }) => {
            console.log(page, sorts, form, "----");
            // 默认接收 Promise<{ result: [], page: { total: 100 } }>
            let result = await getInspectionTaskTemplateSamplingItemByPage({
              ...page,
              ...form,
              inspectionTaskId: this.selectData.id,
              fillType: this.selectData.fillType,
            });
            return {
              result: result.data.records,
              page: {
                total: result.data.total,
              },
            };
          },
        },
      },
    };
    const remoteConfig = {};
    const showPopup = false;
    const showPopup2 = false;
    const showPopup3 = false;
    const showPopup4 = false;
    const modalOptions = {
      title: "新建质检任务",
      width: "80%",
      height: 600,

      escClosable: true,
      resize: true,
      showMaximize: true,
      //禁止拖动
      draggable: true,
      destroyOnClose: true,
    };
    const modalOptions4 = {
      title: "新建质检任务",
      width: "80%",

      escClosable: true,
      resize: true,
      showMaximize: true,
      //禁止拖动
      draggable: true,
    };
    const sexListItemRender = {
      name: "VxeSelect",
      options: [
        // { label: "女", value: "Women" },
        // { label: "男", value: "Man" },
      ],
      props: {
        clearable: true,
        filterable: true,

        remote: true,
        remoteConfig: {
          queryMethod: async ({ searchValue }) => {
            console.log("====>测试===>");
            let result = await getInspectionTemplateByPage({
              currentPage: 1,
              pageSize: 10,
            });
            this.sexListItemRender.options = result.data.records.map((item) => {
              return {
                value: item.id,
                label: item.code,
              };
            });
            console.log(
              sexListItemRender.options,
              "==>sexListItemRender.options"
            );
          },
        },
      },
    };
    const materialListItemRender = {
      name: "VxeSelect",
      options: [
        // { label: "女", value: "Women" },
        // { label: "男", value: "Man" },
      ],
      props: {
        clearable: true,
        filterable: true,

        remote: true,
        remoteConfig: {
          queryMethod: async ({ searchValue }) => {
            console.log(searchValue, "====>测试===>");
            let result = await getMaterialByPage({
              currentPage: 1,
              pageSize: 10,
              code: searchValue,
            });
            this.materialListItemRender.options = result.data.records.map(
              (item) => {
                return {
                  value: item.code,
                  label: item.code,
                };
              }
            );
            console.log(
              materialListItemRender.options,
              "==>sexListItemRender.options"
            );
          },
        },
      },
    };

    const formOptions = {
      data: {
        id: 0,
        code: "",
        name: "",
        level: "",
      },
      rules: {
        name: [{ required: true, message: "名称必填" }],
        code: [{ required: true, message: "编码必填" }],
      },
      items: [
        {
          field: "code",
          title: "编码",
          span: 24,
          itemRender: { name: "VxeInput" },
        },
        {
          field: "name",
          title: "名称",
          span: 24,
          itemRender: { name: "VxeInput" },
        },
        {
          field: "qty",
          title: "数量",
          span: 24,
          itemRender: { name: "VxeNumberInput", props: { type: "integer" } },
        },
        {
          field: "materialCode",
          title: "青选择物料",
          span: 24,
          itemRender: materialListItemRender,
        },
        {
          field: "inspectionTemplateId",
          title: "请选择质检模板",
          span: 24,
          itemRender: sexListItemRender,
        },
        {
          align: "center",
          span: 24,
          itemRender: {
            name: "VxeButtonGroup",
            options: [
              { type: "submit", content: "提交", status: "primary" },
              { type: "reset", content: "重置" },
            ],
          },
        },
      ],
    };

    const formOptions2 = {
      data: {
        id: 0,
        materialCode: "",
        orNo: "",
        qty: "",
      },
      rules: {
        name: [{ required: true, message: "名称必填" }],
        code: [{ required: true, message: "编码必填" }],
      },
      items: [
        {
          field: "materialCode",
          title: "物料编码",
          span: 6,
          // itemRender: { name: "VxeInput" },
        },
        {
          field: "name",
          title: "来料",
          span: 6,
          // itemRender: { name: "VxeInput" },
        },
        {
          field: "orNo",
          title: "批次号",
          span: 6,
          // itemRender: { name: "VxeInput" },
        },
        {
          field: "qty",
          title: "数量",
          span: 6,
          // itemRender: { name: "VxeNumberInput", props: { type: "integer" } },
        },
      ],
    };
    const formRules = {
      scanBarcode: [{ required: true, message: "必须填写" }],
      workstationId: [{ required: true, message: "必须填写" }],
      workNo: [
        {
          required: true,
          pattern: "\\d{2}-\\d{5}",
          message: "字母开头5~10位数",
        },
      ],
      teamId: [{ required: true, message: "必须填写" }],
      rawMaterial: [{ required: true, message: "必须填写" }],
      // rawMaterial: [
      //   {
      //     required: true,
      //     pattern: "^[a-zA-Z]\\w{5,7}$",
      //     message: "字母开头5~10位数",
      //   },
      // ],
      // role: [{ required: true, message: "必须填写" }],
    };
    const todos = [
      { name: "1", value: "1" },
      { name: "2", value: "2" },
      { name: "3", value: "2" },
      { name: "4", value: "2" },
      { name: "5", value: "2" },
    ];
    const formData = {
      //二维码
      scanBarcode: "",
      workstationId: "", //工位信息
      workNo: "", //工单信息
      proceduresName: "工序信息",
      equipmentId: null,
      teamId: "",
      worker: "",
      remark: "",
      rawMaterial: "",
      rollNums: "",
      materialCode: "",
      materialName: "",
      weight: "",
      planTime: "",
    };
    const uploadMethod = async ({ file }) => {
      const formData = new FormData();
      formData.append("file", file);
      let result = await uploadFile(formData);
      console.log(result, "===>result===>");
      console.log(this.fileList, "====>result===>");
    };
    return {
      border: true,
      gridOptions,
      gridOptions2,
      showPopup,
      showPopup2,
      showPopup3,
      showPopup4,
      modalOptions,
      modalOptions4,
      selectTab: "性能",
      titleBackground: false,
      fileList,
      sexListItemRender,
      materialListItemRender,
      formOptions,
      formOptions2,
      formRules,
      todos,
      formData,
      loading: false,
      uploadMethod,
      selectData,
      // remoteConfig,
    };
  },
  created() {},
  methods: {
    toolbarButtonClickEvent(params) {
      if (params.code == "myAdd") {
        this.showPopup = true;
        this.modalOptions.width = 800;
        this.modalOptions.height = "";
      } else {
        const $grid = this.$refs.gridRef;
        if ($grid) {
          const selectRecords = $grid.getCheckboxRecords();
          if (selectRecords.length <= 0) {
            VxeUI.modal.message({ content: `请先选择数据`, status: "warning" });
          }
        }
      }
      console.log(params.code);
    },
    tabChangeEvent({ name }) {
      console.log(name, "===>name===");
      this.selectData.fillType = name;
      if (name == "性能") {
        const $grid2 = this.$refs.gridRef2.commitProxy("reload");
      } else {
        const $grid3 = this.$refs.gridRef3.commitProxy("reload");
      }
    },
    formSubmitEvent() {
      console.log("form submit");
    },
    formResetEvent() {
      console.log("form reset");
    },
    //表单的提交
    async submitEvent() {
      this.loading = true;
      try {
        let result = await addInspectionTasks([{ ...this.formOptions.data }]);
        console.log("保存成功", JSON.stringify(this.formOptions.data));
        VxeUI.modal.message({ content: "保存成功", status: "success" });
        const $grid = this.$refs.gridRef.commitProxy("reload");
        this.loading = false;
        this.showPopup = false;
      } catch (error) {
        this.loading = false;
      } finally {
        // const $grid = this.$refs.gridRef.commitProxy("reload");
      }
    },
    //表单的重置
    resetEvent() {
      console.log("重置事件");
    },
    downloadTmp(row) {
      // fetch(
      //   "http://127.0.0.1:9300/statics/2025/10/17/工位信息_20251017143238A004.xlsx"
      // )
      //   .then((response) => response.blob())
      //   .then((blob) => {
      //     VxeUI.saveFile({
      //       filename: "文件名",
      //       content: blob,
      //     });
      //   });

      download(
        "system/inspectionTask/downloadTmpData",
        { ...row },
        `downloadTmpData_${new Date().getTime()}.xlsx`
      );
    },
    async fillDate(row) {
      console.log(row, "====>===>");
      this.showPopup3 = true;
      // this.$nextTick(() => {
      this.selectData = row;
      this.selectData.fillType = "性能";
      this.selectData.id = row.id;
      this.selectData.materialCode = row.materialCode;
      this.selectTab = "性能";

      this.modalOptions.title = "填写质检数据";
      this.modalOptions.width = "80%";
      this.modalOptions.height = 600;
      this.formOptions2.data = row;
      // });

      // const $grid = this.$refs.gridRef2.commitProxy("reload");

      // const result = await getValueTmpByTaskId(row);
      // this.todos = result.data;
    },
    uploadTmp(row) {
      this.showPopup2 = true;
      this.modalOptions.title = "请上传质检模板";
    },
    updateRow(row) {
      this.formOptions.data = row;
      this.showPopup = true;
      console.log(row.id, "---row---");
    },
    async deploy(row) {
      this.formOptions.data = row;
      console.log(row.id, "---row---");
      await camundaModelDeploymentById(row);
    },
    async confirmEvent2() {
      console.log(this.todos, "===>todos====");
      // const params = [];
      if (this.selectTab == "性能") {
        // params = this.$refs.gridRef2.getFullData();
        console.log(this.$refs.gridRef2.getFullData());
        await fillInspectionSamplingTaskValue(
          this.$refs.gridRef2.getFullData()
        );
      } else {
        // params = this.$refs.gridRef3.getFullData();
        console.log(this.$refs.gridRef3.getFullData());
        await fillInspectionSamplingTaskValue(
          this.$refs.gridRef3.getFullData()
        );
      }

      // await fillInspectionTaskValue(this.todos);
    },
    async confirmEvent3() {
      console.log("===>", this.todos);
      await fillInspectionTaskValueExt(this.todos);
    },
    async confirmEvent() {},

    moreFillData(row) {
      this.showPopup4 = true;
      console.log(row.fillQty - 3);
      this.todos = [];
      for (let i = 0; i < row.fillQty - 3; i++) {
        const indexi = i + 4;
        this.todos.push({ value: "", name: "值" + indexi, code: indexi });
      }
      this.selectSubData = row;
    },
    async deleteData(row) {
      await delInspectionTask({ id: row.id });
      const $grid = this.$refs.gridRef.commitProxy("reload");
      VxeUI.modal.message({ content: "删除成功", status: "success" });
    },
  },
};
</script>
